<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="路线编号" prop="shiftName">
            <el-input placeholder="请输入路线编号" v-model="queryParams.routeId" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="线路名称" prop="shiftName">
            <el-input placeholder="请输入路线名称" v-model="queryParams.routeName" clearable style="width: 240px" />
          </el-form-item>
          <el-form-item label="备注说明" prop="shiftName">
            <el-input placeholder="请输入" clearable v-model="queryParams.remark" style="width: 240px" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:shift:add']">新增</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:shift:edit']"
              >修改</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:shift:remove']"
              >删除</el-button
            >
          </el-col>
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:shift:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        :row-key="(row) => row.routeId "
        height="calc(100vh - 360px)"
        v-loading="loading"
        :data="studentRecognitionRecordList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="routeId" />
        <el-table-column label="线路名称" align="center" prop="routeName" />
        <el-table-column label="负责人" align="center" prop="director" />
        <el-table-column label="联系电话" align="center" prop="phone" />
        <el-table-column label="线路巡检点" align="center" prop="spotCount" />
        <el-table-column label="备注" align="center" prop="remark" />
        <el-table-column label="最后修改人" align="center" prop="updateByName" />
        <el-table-column label="最后修改时间" align="center" prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生识别记录对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="600px" append-to-body>
      <el-form ref="studentRecognitionRecordFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="路线名称" prop="routeName">
          <el-input v-model="form.routeName" placeholder="请输入路线名称" />
        </el-form-item>
        <el-form-item label="负责人">
          <el-input v-model="form.director" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="巡检点" v-if="form.routeId">
          <!-- <el-button type="primary" :icon="Plus" size="small" @click="onClickAdd">添加</el-button> -->
          <!-- <el-button type="danger" :icon="Delete" size="small" @click="onClickDelete" :disabled="selectData.length === 0">删除</el-button> -->
          <el-button type="primary" :icon="FolderChecked" size="small" @click="onClickMigrate">迁移</el-button>
          <div class="row-grid attrs-table">
            <div class="row-grid-header">
              <div class="row-grid-tr">
                <div class="row-grid-td serial">
                  序号 <el-checkbox style="margin-left: 10px;" v-model="checkAll" @change="onChangeCheckBoxAll"></el-checkbox>
                </div>
                <div class="row-grid-td namemax row-grid-center">点编号</div>
                <div class="row-grid-td name1">点名称</div>
              </div>
            </div>
            <draggable
              class="row-grid--draggable"
              v-model="selectData"
              chosenClass="row-grid-tr--chosen"
              ghostClass="row-grid-tr--ghost"
              dragClass="row-grid-tr--drag"
              :forceFallback="true"
              :item-key="(item: any) => item.routeId"
              handle=".serial"
              @start="true"
              @end="draggerEnd"
            >
              <template #item="{ element, index }">
                <div class="row-grid-tr">
                  <div class="row-grid-td serial">
                    <el-icon>
                      <Sort />
                    </el-icon>
                    {{ index + 1 }}
                  </div>
                  <div class="row-grid-td name1">
                    <el-checkbox v-model="element.checked"></el-checkbox>
                  </div>
                  <div class="row-grid-td namemax">
                    {{element.spotId}}
                  </div>
                  <div class="row-grid-td namemax">
                    {{element.spotName}}
                  </div>
                </div>
              </template>
            </draggable>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <migrate :visible="migrateVisible" @closeDialog="closeMigrateDialog" :params="migrateParams" />
  </div>
</template>

<script setup name="Inspectionroute" lang="ts">
import {
  ApiGetInspectionRouteList,
  ApiCreateInspectionRoute,
  ApiUpdateInspectionRoute,
  ApiGetInspectionRouteDetail,
  ApiDeleteInspectionRoute
} from '@/api/inspection/inspectionroute';
import { pageQuery, inspectionrouteForm } from '@/api/inspection/inspectionroute/types';
import { FolderChecked, Plus } from '@element-plus/icons-vue';
import migrate from './childrens/migrate.vue';
import draggable from 'vuedraggable';
import { get } from '@vueuse/core';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const studentRecognitionRecordList = ref<pageQuery[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<any>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRangeRecognizeTime = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const studentRecognitionRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: inspectionrouteForm = {
  routeId: '', // 路线ID
  routeName: '', // 路线名称
  remark: '', // 备注
  director: '', // 负责人
  phone: '', // 联系电话
  xjSpotList: []
};

const phoneValidator = (rule: any, value: string, callback: any) => {
  const reg = /^1[3-9]\d{9}$/;
  if (value!=='' && !reg.test(value)) {
    callback(new Error('请输入正确的手机号'));
  } else {
    callback();
  }
};

const data = reactive<PageData<inspectionrouteForm, pageQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    routeId: '', // 路线ID
    routeName: '', // 路线名称
    remark: '' // 备注
  },
  rules: {
    routeName: [{ required: true, message: '路线名称不能为空', trigger: 'blur' }],
    phone: [{ required: false, validator: phoneValidator, trigger: ['blur', ], }],
  }
});


const migrateVisible = ref(false);
const migrateParams = ref<any>({});
const selectData: any = ref([]);
const checkAll = ref(false);

const { queryParams, form, rules } = toRefs(data);
/** 查询学生识别记录列表 */
const getList = async () => {
  loading.value = true;
  const res = await ApiGetInspectionRouteList(queryParams.value);
  studentRecognitionRecordList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentRecognitionRecordFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRangeRecognizeTime.value = ['', ''];
  queryFormRef.value?.resetFields();
  queryParams.value.routeId=""
  queryParams.value.routeName=""
  queryParams.value.remark=""
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: inspectionrouteForm[]) => {
  ids.value = selection.map((item) => item.routeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加巡检路线';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: inspectionrouteForm) => {
  reset();
  const _id = row?.routeId;
  const res = await ApiGetInspectionRouteDetail(_id);
  Object.assign(form.value, res.data);
  selectData.value = res.data?.xjSpotList.length > 0 && res.data?.xjSpotList[0] !== null ? res.data?.xjSpotList.map((item: any) => {
    item.checked = false;
    return item;
  }) : [];
  dialog.visible = true;
  dialog.title = '修改巡检路线';
};

/** 提交按钮 */
const submitForm = () => {
  studentRecognitionRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.routeId) {
        form.value.xjSpotList = JSON.parse(JSON.stringify(selectData.value)).map((item: any, index: number) => {
        return {
          spotId: item.spotId,
          sort: index + 1
        }
      }) || [];
        await ApiUpdateInspectionRoute(form.value).finally(() => (buttonLoading.value = false));
      } else {
        form.value.xjSpotList = JSON.parse(JSON.stringify(selectData.value)).map((item: any, index: number) => {
        return {
          spotId: item.spotId,
          sort: index + 1
        }
      }) || [];
        await ApiCreateInspectionRoute(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: inspectionrouteForm) => {
  if(!row){
    await proxy?.$modal.confirm('是否确认删除选中的"' + ids?.value?.length + '"条数据？').finally(() => (loading.value = false));
    await ApiDeleteInspectionRoute(ids.value);
    proxy?.$modal.msgSuccess('删除成功');
  }else{
    const _ids = row?.routeId;
  await proxy?.$modal.confirm('是否确认删除线路名称为"' + row.routeName + '"的数据项？').finally(() => (loading.value = false));
  await ApiDeleteInspectionRoute(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  }
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/studentRecognitionRecord/export',
    {
      ...queryParams.value
    },
    `studentRecognitionRecord_${new Date().getTime()}.xlsx`
  );
};

const closeMigrateDialog = () => {
  migrateVisible.value = false;
  getList();
};


// const onClickAdd = () => {
//   addCheckVisiable.value = true;
// };

// const onClickDelete = () => {
//   console.log(selectData.value, 'selectData');
//   if (!selectData.value.some((item: any) => item.checked === true)) {
//     return ElMessage.error('请选择要删除的项');
//   }
//   // 判断selectData中是否有checked的 或者 checked为true
//   selectData.value = JSON.parse(JSON.stringify(selectData.value.filter((item: any, index: number) => !(item.checked || false))));
//   console.log('删除后：', selectData.value);
// };
const onClickMigrate = () => {
    if (!selectData.value.some((item: any) => item.checked === true)) {
    return ElMessage.error('请选择要迁移的巡检点');
  }
  migrateVisible.value = true;
  migrateParams.value = {
    routeId: form.value.routeId,
    xjSpotList: JSON.parse(JSON.stringify(selectData.value)).filter((item: any) => (item.checked)).map((item: any, index: number) => {
        return {
          spotId: item.spotId,
          sort: index + 1
        }
      }) || []
  };
}

//拖拽结束事件
const draggerEnd = (v: any) => {
  //
}

const onChangeCheckBoxAll = (val: any) => {
  console.log(val, 'val')
  if (val) {
    selectData.value = selectData.value.map((item: any) => {
      item.checked = true;
      return item;
    })
  } else {
    selectData.value = selectData.value.map((item: any) => {
      item.checked = false;
      return item;
    })
  }
}

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>

@import '@/assets/styles/variables.module';
$--border-color-lighter: #edf0f5;
$--background-color-base: #f6f6f6;
$--color-text-regular: #646666;
.row-grid {
  position: relative;
  width: 100%;
  font-size: 14px;
  overflow: hidden;
  margin-top: 20px;
  margin-bottom: 10px;
  border: 1px solid $--border-color-lighter;
  border-radius: 10px;
  background-color: #fff;

  &-header {
    background-color: $--background-color-base;
  }

  &-tr {
    display: flex;
    align-items: center;
    width: 100%;

    & + .row-grid-tr {
      border-top: 1px solid $--border-color-lighter;
    }

    &--chosen {
      cursor: move;
    }

    &--ghost {
      opacity: .5;
      background-color: #f6f8fa;
    }
  }

  &-th, &-td {
    padding: 10px 16px;
    flex: auto;
    color: $--color-text-regular;
    line-height: 1.5
  }

  &-footer {
    border-top: 1px solid $--border-color-lighter;
  }

  &-empty {
    padding: 16px;
    text-align: center;
    color: $--color-text-regular;
  }

  &-right {
    text-align: right;
  }

  &-center {
    text-align: center;
  }

  &--bordered {
    .row-grid-th,
    .row-grid-td {
      & + .row-grid-th,
      & + .row-grid-td {
        border-left: 1px solid $--border-color-lighter;
      }
    }
  }
}

.attrs-table {
  width: 740px;
  line-height: 20px;
  border: 1px solid #edf0f5;

  .row-grid--draggable {
    :deep(.el-form-item__content) {
      justify-content: space-around;
    }
    .row-grid-tr {
      .serial {
        cursor: grab;
      }

      &--chosen {
        .serial {
          cursor: move;
        }
      }

      &--ghost {
        opacity: 0.1;
      }

      &--drag {
        border-bottom: 1px solid #edf0f5;
        background-color: #fff;
      }
    }
  }

  .row-grid-td {
    width: 160px;
    white-space: nowrap;

    &.serial {
      width: 40px;
      text-align: left;
      .sort {
        position: relative;
        color: #969999;
        vertical-align: middle;
        margin: 0 4px 0 -4px;
      }
    }

    &.name1 {
      width: 100px;
      text-align: center;
    }

    &.namemax {
      width: 300px;
      text-align: center;
    }

    &.action {
      width: 70px;
    }

    & + .row-grid-td {
      padding-left: 0;
    }
  }
}
</style>
